package sren.serialtest

import javafx.beans.property.*
import scalafx.application.JFXApp3
import scalafx.application.JFXApp3.PrimaryStage
import scalafx.collections.*
import scalafx.scene.Scene
import scalafx.scene.control.*
import scalafx.scene.layout.*

import scala.concurrent.{ExecutionContext, Future}

object SerialTool extends JFXApp3 {

  given ec: ExecutionContext = ExecutionContext.global

  val serialObj = new SerialObj

  val isConnected = new SimpleBooleanProperty(false)

  val output = new SimpleStringProperty()

  lazy val toolBar = new ToolBar {
    this.items = Seq(
      new ChoiceBox[String] {
        val lst = new ObservableBuffer[String]()
        serialObj.getPorts().map(p => lst.add(p.getSystemPortName))
        this.items.setValue(lst)
      },
      new Button("连接") {
        disable.bind(isConnected)
        onAction = (e) => {
          output.set(output.get().appendedAll("connect... \n"))
          serialObj.connect("ttyUSB0")
          Future {
            while (true) {
              while (serialObj.is.available() <= 0) {
                Thread.sleep(20)
              }
              val buf = new Array[Byte](1024)
              val readed = serialObj.is.read(buf)
              output.setValue(output.getValue ++ new String(buf.take(readed)))
            }
          }
          isConnected.set(true)
        }
      },
      new Button("断开") {
        disable.bind(isConnected.not())
        onAction = (e) => {
          output.set(output.get().appendedAll("disconnect... \n"))
          serialObj.disConnect()
          isConnected.set(false)
        }
      },
      new Button("退出") {
        onAction = (e) => {
          System.exit(0)
        }
      }
    )
  }

  override def start(): Unit = {
    stage = new PrimaryStage {
      width = 800
      height = 450
      title = "Serial Tool"
      scene = new Scene {
        this.getStylesheets.add("Main.css")
        content = new BorderPane {
          top = toolBar
          center = new TextArea {
            this.text.bind(output)
          }
        }
      }
    }
  }
}
